/* eslint-disable react/jsx-indent */
/* eslint-disable react/jsx-closing-tag-location */
import React, { PureComponent } from 'react';
import { connect } from 'dva';

import {
  DownloadOutlined,
  DownOutlined,
  EllipsisOutlined,
  ExclamationCircleOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';

import {
  Row,
  Col,
  Card,
  Button,
  Dropdown,
  Menu,
  Modal,
  message,
  Divider,
  Tabs,
  Checkbox,
  Tooltip,
  Progress,
} from 'antd';
import queryString from 'query-string';
import moment from 'moment';
import Link from 'umi/link';
import router from 'umi/router';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import ProTable from '@/pages/components/Problem/ProblemPage/ProTable';
import ProModal from '@/pages/components/Problem/ProblemPage/ProModal';
import ProExportBtn from '@/pages/components/Problem/ProblemPage/ProExportBtn';
import { checkPermissions } from '@/utils/authority';
import Authorized from '@/utils/Authorized';
import downloadFile, { getProPagination } from '@/utils/utils';
import styles from '../../../utils/utils.less';
import proIcon from '../../../assets/proIcon.png';
import ContactPhone from './ContactPhone';
import careerStyle from './careerStyle.less';
import RenderForm from './RenderForm';

const { TabPane } = Tabs;
const { confirm } = Modal;
const formItemLayout2 = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 6,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 18,
    },
  },
};
@connect(({ career, loading, dimission: { proListData }, login }) => ({
  data: career.data,
  proObjData: career.proObjData,
  formFieldsValue: career.formFieldsValue,
  activeKey: career.activeKey,
  pageOrdBys: career.pageOrdBys,
  tabList: career.tabList,
  expandForm: career.expandForm,
  loading: loading.models.career || loading.models.dimission,
  proListData,
  login,
  proVisible: career.proVisible,
  pdArrList: career.pdArrList,
  showProgress: career.showProgress,
  downloadParams: career.downloadParams,
  progressPercent: career.progressPercent,
}))
@Form.create()
class TableList extends PureComponent {
  state = {
    // 单条问题人员各种状态
    proStatus: [],
    // confirmLoading: false,
    selectedRows: [],
    selectedRowKeys: [],
    contactWayList: [
      { itemCode: '1', itemName: '电话' },
      { itemCode: '2', itemName: '短信' },
      { itemCode: '3', itemName: '邮件' },
    ],
    conatctVisible: false,
    contactFlag: '2',
    expandConsult: false,
    fromAttr: [
      'empName',
      'certNo',
      'custId',
      'areaId',
      'creName',
      'execState',
      'matState',
      'dateArr',
      'contState',
      'tskName',
      'contTypes',
      'creId',
      'tskId',
    ],
    tableDateTit: [
      {},
      {},
      { dataIndex: 'operTime', title: '办理时间' },
      { dataIndex: 'subExecTime', title: '办理完成时间' },
      { dataIndex: 'operTime', title: '取消操作时间' },
    ],
    checked: false,
    proTable: {},
  };

  componentDidMount() {
    const {
      location,
      activeKey,
      pageOrdBys,
      dispatch,
      data: { pagination },
      login,
    } = this.props;
    const { isMenuLink } = queryString.parse(location.search);
    const tempActiveKey = queryString.parse(location.search).activeKey || activeKey;
    const { baseUser } = login;
    dispatch({
      type: 'career/updateModelData',
      payload: {
        activeKey: tempActiveKey,
        formFieldsValue: { tskId: baseUser.userId },
      },
    });
    const proPagination = getProPagination(tempActiveKey, '5', pagination);
    if (isMenuLink) {
      this.resetAndGeLlist(location);
    } else {
      this.getList(tempActiveKey, pageOrdBys, proPagination.current, proPagination.pageSize);
    }
  }

  // 查询列表
  getList = (
    activeKey = '1',
    pageOrdBys,
    currentPage = 1,
    pageSize = 10,
    queryParam,
    isClear = true
  ) => {
    if (isClear) {
      this.setState({
        selectedRowKeys: [],
        selectedRows: [],
      });
    }
    const { dispatch, form, login } = this.props;
    const { fromAttr } = this.state;
    const { baseUser } = login;
    form.validateFields(fromAttr, (err, fieldsValue) => {
      if (err) return;
      const newFieldsValue = queryParam || fieldsValue;
      dispatch({
        type: 'career/updateModelData',
        payload: { formFieldsValue: newFieldsValue, activeKey },
      });
      const formFieldsValue = {};
      if (Object.keys(newFieldsValue).indexOf('tskId') === -1) {
        newFieldsValue.tskId = baseUser.userId;
      }
      Object.keys(newFieldsValue).forEach(key => {
        if (key === 'dateArr') {
          if (newFieldsValue.dateArr && newFieldsValue.dateArr.length) {
            formFieldsValue.startDate = newFieldsValue.dateArr[0].format('YYYY-MM-DD') || null;
            formFieldsValue.endDate = newFieldsValue.dateArr[1].format('YYYY-MM-DD') || null;
          }
          delete formFieldsValue[key];
        } else if (key === 'areaId' && newFieldsValue[key] && newFieldsValue[key].key) {
          formFieldsValue[key] =
            newFieldsValue[key].key === undefined ? null : newFieldsValue[key].key;
        } else if (key !== 'contTypes' && key !== 'areaId') {
          formFieldsValue[key] =
            newFieldsValue[key] === undefined ? null : newFieldsValue[key].trim();
        }
      });
      const values = {
        curStep: activeKey,
        ...formFieldsValue,
        contTypes: newFieldsValue.contTypes,
        pageOrdBys,
        pagerArg: { currentPage, pageSize },
      };
      const downloadParams = {
        curStep: activeKey,
        ...formFieldsValue,
        contTypes: newFieldsValue.contTypes,
        busiType: 1,
      };
      dispatch({
        type: 'career/updateModelData',
        payload: {
          downloadParams,
          downloadParams1: { ...values },
        },
      });
      if (Number(activeKey) === 5) {
        setTimeout(() => {
          const { proTable } = this.state;
          const proFormFieldsValue = { ...downloadParams };
          if (proTable.searchList) {
            proTable.searchList(proFormFieldsValue, currentPage, pageSize);
          }
        });
      } else {
        dispatch({
          type: 'career/fetchList',
          payload: values,
        });
      }
    });
  };

  // 重置
  resetSearch = () => {
    const { form, dispatch, login } = this.props;
    const { baseUser } = login;
    form.resetFields();
    form.setFieldsValue({ dateArr: null, tskId: baseUser.userId });
    dispatch({
      type: 'career/updateModelData',
      payload: { formFieldsValue: { tskId: baseUser.userId } },
    });
  };

  // 问题人员入参
  getProData = () => {
    const { dispatch } = this.props;
    const { selectedRowKeys } = this.state;
    dispatch({
      type: 'career/fetchProData',
      payload: { entryIds: selectedRowKeys },
    });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { activeKey, dispatch } = this.props;
    let ordBy = null;
    if (sorter.order) {
      ordBy = sorter.order === 'ascend' ? 'ASC' : 'DESC';
    }
    const pageOrdBys = [
      {
        property: sorter.field || null,
        ordBy,
      },
    ];
    dispatch({
      type: 'career/updateModelData',
      payload: { pageOrdBys },
    });
    this.getList(activeKey, pageOrdBys, pagination.current, pagination.pageSize, undefined, false);
  };

  // 切换表格展开收起
  toggleForm = () => {
    const { dispatch, expandForm, login, form, formFieldsValue } = this.props;
    const { baseUser } = login;
    if (expandForm) {
      form.setFieldsValue({ tskId: baseUser.userId });
      dispatch({
        type: 'career/updateModelData',
        payload: {
          formFieldsValue: { ...formFieldsValue, tskId: baseUser.userId },
        },
      });
    }
    dispatch({
      type: 'career/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
    this.toggleProModal(false);
  };

  // 切换标签
  changeTabPane = activeKey => {
    const { location } = this.props;
    const pageOrdBys = [{ property: null, ordBy: null }];
    router.push({
      pathname: location.pathname,
      query: {
        activeKey,
      },
    });
    this.getList(activeKey, pageOrdBys);
  };

  // 收材料
  collectMaterial = record => {
    const { dispatch, activeKey } = this.props;
    const { entryId } = record;
    if (Number(activeKey) === 1) {
      dispatch({
        type: 'career/getCareerMat',
        payload: { entryId },
        callback: res => {
          if (res.success) {
            const { matPkgVo } = res.data;
            if (!(JSON.stringify(matPkgVo) === '{}' || matPkgVo === undefined)) {
              router.push(
                `/careermanage/career/collectMaterial?entryId=${
                  record.entryId
                }&&activeKey=${activeKey}&&execState=${record.execState}`
              );
            }
          } else {
            message.warning(res.message || '服务端错误');
          }
        },
      });
    }
    if (Number(activeKey) === 2 || Number(activeKey) === 3) {
      router.push(
        `/careermanage/career/updatematerial?entryId=${
          record.entryId
        }&&activeKey=${activeKey}&&execState=${record.execState}`
      );
    }
    dispatch({
      type: 'career/listData',
      payload: record,
    });
    dispatch({
      type: 'career/updateModelData',
      payload: { currentSelectedRows: [record], currentSelectedRowKeys: [record.entryId] },
    });
  };

  // 联系
  sendNote = code => {
    this.setState({
      contactWayCode: code,
    });
    const { selectedRows } = this.state;
    const that = this;
    // 非电话
    if (Number(code) !== 1) {
      if (selectedRows.length) {
        const dis = selectedRows.some(item => item.entrySource === '2' || item.entrySource === '3');
        const disContact = selectedRows.some(item => item.contState === 3);
        // 判断是不是 待再次联系
        if (dis) {
          message.warning(
            '入职任务来源为‘在职增产品、在职增险种’的，只可使用电话入职联系，不可使用邮件或短信'
          );
        } else {
          const obj = {};
          const arr = [];
          selectedRows.map(item => {
            const obj1 = {};
            obj1.entryId = item.entryId;
            return arr.push(obj1);
          });
          obj.entryContRcrds = arr;
          obj.contactWay = code;
          confirm({
            title: disContact
              ? `已选${selectedRows.length}条数据，所选数据存在已被标记再次联系人员，${
                  +code === 2 ? '短信' : '邮件'
                }发送后，是否保留再次联系标记`
              : `已选${selectedRows.length}条数据，确定要发送${
                  +code === 2 ? '短信' : '邮件'
                }通知吗？`,
            okText: '确定',
            icon: <QuestionCircleOutlined />,
            cancelText: '取消',
            content: disContact && (
              <Checkbox value="1" onChange={this.onRepairBalance}>
                保留再次联系
              </Checkbox>
            ),
            onOk: () => {
              setTimeout(() => {
                const { checked } = this.state;
                that.contactport({ ...obj, concatValue: checked ? 1 : 2 });
              }, 0);
            },
            onCancel() {},
          });
        }
      } else {
        message.warning('至少勾选一条数据');
      }
    } else {
      // 电话
      if (!selectedRows.length) {
        return message.warning('至少勾选一条数据');
      }
      this.handleModalVisible(true);
      this.setState({
        empTel: selectedRows[0].empName,
        conTel: selectedRows[0].phone,
        expandConsult: false,
        contactFlag: false,
        multiterm: selectedRows.length > 1,
      });
    }
    return true;
  };

  // 是否保持再次联系
  onRepairBalance = e => {
    this.setState({ checked: e.target.checked });
  };

  // 电话联系
  submitData = operms => {
    const { contactWayCode, selectedRows } = this.state;
    const entryContRcrds = selectedRows.map(item => ({ entryId: item.entryId }));
    const values = {
      consultRcrd: {
        replyContent: operms.replyContent,
        state: operms.state,
        content: operms.content,
      },
      contactWay: contactWayCode,
      contactContent: operms.contactContent,
      againFlag: operms.againFlag,
      againTime: operms.againTime ? operms.againTime.format('YYYY-MM-DD') : null,
      consultRcrdFlag: operms.consultRcrdFlag,
      entryContRcrds,
    };
    this.contactport(values);
  };

  // 电话联系
  contactport = obj => {
    const { dispatch, activeKey, pageOrdBys } = this.props;
    dispatch({
      type: 'career/contactAdd',
      payload: obj,
      callback: response => {
        if (response.success) {
          // 短信或者邮箱发送部分成功时候标题（'tit'）和内容（12233）
          if (+obj.contactWay === 1) {
            this.setState({
              conatctVisible: false,
            });
          } else {
            dispatch({
              type: 'career/updateModelData',
              payload: { contactWay: obj.contactWay },
            });
            this.setState({
              checked: false,
            });
          }
          this.getList(activeKey, pageOrdBys);
        } else {
          message.warning(response.message || '服务端错误');
        }
      },
    });
  };

  // 模态框显隐
  handleModalVisible = flag => {
    this.setState({
      conatctVisible: !!flag,
    });
  };

  // 取消
  conatctCancel = () => {
    this.setState({
      conatctVisible: false,
    });
  };

  // 联系记录数据
  contactData = value => {
    this.setState({ contactFlag: value });
  };

  // 联系记录弹窗
  addConsultData = expandConsult => {
    this.setState({
      expandConsult,
    });
  };

  // 办理完成弹窗
  batchToSumbit = () => {
    const { selectedRowKeys, selectedRows } = this.state;
    const { activeKey, pageOrdBys } = this.props;
    if (selectedRowKeys.length > 1) {
      const arr = [];
      selectedRowKeys.forEach(item => {
        const obj = {};
        obj.entryId = item;
        obj.pdAttrs = [];
        arr.push(obj);
      });
      const that = this;
      confirm({
        title: `已选择${selectedRows.length}条数据，确认全部标记为办理完成吗？`,
        icon: <QuestionCircleOutlined />,
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          that.props.dispatch({
            type: 'career/updateExceState',
            payload: arr,
            callback: response => {
              if (response.success) {
                if (response.data.success) {
                  this.getList(activeKey, pageOrdBys);
                  message.success('提交成功');
                } else {
                  Modal.warning({
                    title: '提交成功',
                    content: response.data.message,
                    okText: '关闭',
                    okType: 'default',
                    autoFocusButton: 'cancel',
                    onOk: () => {
                      this.getList(activeKey, pageOrdBys);
                    },
                  });
                }
              }
            },
          });
        },
        onCancel() {},
      });
    } else if (Number(selectedRowKeys.length) === 1) {
      if (Number(selectedRows[0].execState) === 1) {
        this.runSumbit(selectedRows[0]);
      } else {
        message.warning('此操作只针对申报状态为待提交的员工');
      }
    } else {
      message.warning('至少选择一条数据');
    }
  };

  // 弹窗统一处理
  runSumbit = record => {
    if (Array.isArray(record.entryDetails)) {
      const flag = record.entryDetails.some(
        item => Number(item.execState) === 1 && Number(item.probFlag) === 2
      );
      if (!flag) {
        return Modal.error({
          title: '提交失败',
          content: '此雇员为问题人员，不能标记办理完成',
          okText: '关闭',
          okType: 'default',
          autoFocusButton: 'cancel',
        });
      }
    }
    const { dispatch } = this.props;
    dispatch({
      type: 'career/listData',
      payload: record,
    });
    this.setState({
      execVisable: true,
      entryId: record.entryId,
    });
    return null;
  };

  // 提交运行 ok
  execOk = () => {
    const { dispatch, form, activeKey, pageOrdBys } = this.props;
    this.setState({
      execVisable: false,
    });
    form.validateFields(['pdArrAccu', 'pdArrSocial'], (err, fieldsValue) => {
      const pdAttr = [];
      const obj = {};
      const socialArr = fieldsValue.pdArrSocial;
      const accuArr = fieldsValue.pdArrAccu;
      if (socialArr) {
        Object.keys(socialArr).forEach(key => {
          pdAttr.push(`${socialArr[key]}`);
        });
      }
      if (accuArr) {
        Object.keys(accuArr).forEach(key => {
          pdAttr.push(`${accuArr[key]}`);
        });
      }
      const { entryId } = this.state;
      obj.entryId = entryId;
      obj.pdAttrs = pdAttr;
      dispatch({
        type: 'career/updateExceState',
        payload: [obj],
        callback: response => {
          if (response.success) {
            message.success('提交成功');
            this.getList(activeKey, pageOrdBys);
            this.setState({
              execVisable: false,
            });
          }
        },
      });
    });
  };

  // 问题人员弹窗
  showModal = () => {
    const { selectedRows } = this.state;
    if (!selectedRows.length) return message.warning('请至少选择一项');
    // 判断是多选还是单选
    if (selectedRows.length === 1) {
      const temArr = [];
      let insMergFlags = 1;
      if (selectedRows[0].entryDetails.length) {
        insMergFlags = selectedRows[0].insMergFlag;
        selectedRows[0].entryDetails.forEach(item => {
          temArr.push({
            ass: item.ass,
            execState: item.execState,
            probFlag: item.probFlag,
            insMergFlag: item.insMergFlag,
            assName: item.assName,
          });
        });
      }
      let problemAll = true;
      let markFailsFlag = true;
      let execAll = true;
      const tipsObj = { tips: [], probTips: [], execTips: [] };
      temArr.forEach(item => {
        if (Number(item.probFlag) === 2) {
          problemAll = false;
        }
        if (Number(item.execState) === 1) {
          execAll = false;
        }
        if (Number(item.execState) === 1 && Number(item.probFlag) === 2) {
          markFailsFlag = false;
        }
      });
      if (problemAll || execAll) {
        if (Number(insMergFlags) === 1) {
          tipsObj.tips.push('社保');
        }
        temArr.forEach(item => {
          if (Number(item.insMergFlag) !== 1) {
            tipsObj.tips.push(item.assName);
          }
        });
      } else {
        if (Number(insMergFlags) === 1) {
          if (
            temArr.filter(item => Number(item.ass) !== 2)[0] &&
            temArr.filter(item => Number(item.ass) !== 2)[0].probFlag === 1
          ) {
            tipsObj.probTips.push('社保');
          } else {
            tipsObj.execTips.push('社保');
          }
        }
        temArr.forEach(item => {
          if (Number(item.probFlag) === 1 && Number(item.insMergFlag) !== 1) {
            tipsObj.probTips.push(item.assName);
          }
          if (Number(item.execState) !== 1 && Number(item.insMergFlag) !== 1) {
            tipsObj.execTips.push(item.assName);
          }
        });
      }
      if (problemAll) {
        const problemTxt = `${selectedRows[0].empName}员工${tipsObj.tips.join(
          ','
        )}已标记问题人员，不可重复标记，请在问题人员列表查看并处理`;
        this.proModalTxt(problemTxt, 'error', '标记失败');
        return true;
      }
      if (execAll) {
        const problemTxt = `${selectedRows[0].empName}员工${tipsObj.tips.join(
          ','
        )}已交接，不可标记问题人员，请联系社保公积金中心服务人员处理`;
        this.proModalTxt(problemTxt, 'error', '标记失败');
        return true;
      }
      this.state.proStatus = temArr;
      if (markFailsFlag) {
        const problemTxt = `${selectedRows[0].empName}员工${tipsObj.execTips.join(
          ','
        )}已交接，不可标记问题人员, ${tipsObj.probTips.join(
          ','
        )}已标记问题人员，不可重复标记，请联系社保公积金中心服务人员处理或在问题人员列表查询处理`;
        this.proModalTxt(problemTxt, 'error', '标记失败');
      } else {
        // this.getProData();
        this.toggleProModal(true);
      }
    } else {
      this.state.proStatus = [];
      // this.getProData();
      this.toggleProModal(true);
    }
    return true;
  };

  // 问题人员弹窗统一处理
  proModalTxt = (problemAllTxt, modalType, tit) => {
    Modal[modalType]({
      title: tit,
      content: problemAllTxt,
      okText: '关闭',
      okType: 'default',
      autoFocusButton: 'cancel',
    });
  };

  // 取消
  execCancel = () => {
    this.setState({
      execVisable: false,
    });
  };

  // 下载
  downExcel = () => {
    const { data, proListData, activeKey, form, login } = this.props;
    const {
      pagination: { total },
    } = data;
    const proTotal = proListData.pagination.total;
    const { baseUser } = login;
    const { fromAttr } = this.state;
    form.validateFields(fromAttr, (err, fieldsValue) => {
      if (err) return;
      const tempVal = fieldsValue;
      const formFieldsValue = {};
      if (!(tempVal.tskId === '')) {
        tempVal.tskId = fieldsValue.tskId || baseUser.userId;
      }
      Object.keys(tempVal).forEach(key => {
        if (key === 'dateArr') {
          if (tempVal.dateArr && tempVal.dateArr.length) {
            formFieldsValue.startDate = tempVal.dateArr[0].format('YYYY-MM-DD') || null;
            formFieldsValue.endDate = tempVal.dateArr[1].format('YYYY-MM-DD') || null;
          }
          delete formFieldsValue[key];
        } else {
          formFieldsValue[key] = tempVal[key] === undefined ? null : tempVal[key].trim();
        }
      });
      formFieldsValue.curStep = String(activeKey) === '5' ? undefined : activeKey;
      if (String(activeKey) === '5') {
        if (Number(proTotal) === 0) {
          message.warning('无查询结果，不可导出');
        } else {
          downloadFile({ ...formFieldsValue, busiType: 1 }, '/esApi/problem/entry/export', 'POST');
        }
      } else {
        if (Number(total) === 0) {
          message.warning('无查询结果，不可导出');
          return;
        }
        downloadFile(formFieldsValue, '/esApi/entry/exportEntryInfo', 'POST');
      }
    });
  };

  // 下载
  outExcel = () => {
    const { activeKey } = this.props;
    const { selectedRowKeys } = this.state;
    if (selectedRowKeys.length) {
      if (Number(activeKey) === 5) {
        this.setState({
          excelLoading: true,
        });
        downloadFile(
          { detIds: selectedRowKeys, busiType: 1 },
          '/esApi/problem/entry/export',
          'POST',
          () => {
            this.setState({
              excelLoading: false,
            });
          }
        );
      } else {
        this.setState({
          excelLoading: true,
        });
        downloadFile(
          { entryIds: selectedRowKeys, curStep: activeKey },
          '/esApi/entry/exportEntryInfo',
          'POST',
          () => {
            this.setState({
              excelLoading: false,
            });
          }
        );
      }
    } else {
      Modal.confirm({
        title: `如果不选择数据，则默认导出当前列表下所有数据`,
        icon: <QuestionCircleOutlined />,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          this.downExcel();
        },
      });
    }
  };

  // 切换标记问题人员modal的显隐
  toggleProModal = flag => {
    const { dispatch } = this.props;
    dispatch({
      type: 'career/toggleProVisible',
      payload: { proVisible: flag },
    });
  };

  batchDeal = () => {
    const activeKey = this.props.activeKey;
    router.push(`/careermanage/career/reImport?activeKey=${activeKey}`);
  };

  // 问题人人员 ok
  proHandleOk = () => {
    const { activeKey, pageOrdBys } = this.props;
    this.getList(activeKey, pageOrdBys);
    this.toggleProModal(false);
  };

  // 切换标记问题人员modal的显隐
  toggleProModal = flag => {
    const { dispatch } = this.props;
    dispatch({
      type: 'career/toggleProVisible',
      payload: { proVisible: flag },
    });
  };

  // 批量反馈
  batchFeedback = () => {
    router.push('/careermanage/career/batchFeedback?busiType=1');
  };

  // 表格申报状态悬浮
  tableDataTip = record => {
    let tip;
    const acuArr = [];
    const socialArr = [];
    const arr = record.entryDetails;
    if (Number(record.insMergFlag) === 1) {
      arr.forEach(item => {
        if (Number(item.ass) === 2) {
          acuArr.push({ ass: '公积金', execStateName: item.execStateName });
        } else {
          socialArr.push({ ass: '社保', execStateName: item.execStateName });
        }
      });
      tip = (
        <p>
          {acuArr.length ? (
            <p>
              <span>{acuArr[0].ass}</span>:<span>{acuArr[0].execStateName}</span>
            </p>
          ) : null}
          {socialArr.length ? (
            <p>
              <span>{socialArr[0].ass}</span>:<span>{socialArr[0].execStateName}</span>
            </p>
          ) : null}
        </p>
      );
    } else {
      tip = arr.map(item => (
        <p key={item.ass}>
          {Number(item.ass) === 2 ? <span>公积金</span> : <span>{item.assName}</span>}:
          <span>{item.execStateName}</span>
        </p>
      ));
    }
    return tip;
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    const { dispatch, pageOrdBys } = this.props;
    const { queryParam } = location;
    await this.resetSearch();
    await this.getList(location.query.activeKey, pageOrdBys, undefined, undefined, queryParam);
    dispatch({
      type: 'career/updateModelData',
      payload: { expandForm: Boolean(queryParam) },
    });
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
  }

  render() {
    const {
      form: { getFieldDecorator },
      loading,
      data,
      proVisible,
      pdArrList,
      tabList,
      activeKey,
      formFieldsValue,
      pageOrdBys,
      expandForm,
      login,
      location: { pathname },
      data: { list },
      progressPercent,
      showProgress,
      downloadParams,
    } = this.props;
    const {
      selectedRows,
      selectedRowKeys,
      contactFlag,
      expandConsult,
      conatctVisible,
      contactWayList,
      empTel,
      execVisable,
      multiterm,
      conTel,
      tableDateTit,
      excelLoading,
      // progressVisible,
    } = this.state;
    const widthFlag = list.some(item => Number(item.overdueFlag) === 1);
    const tempUrl = pathname.split('/index')[0];
    const { baseUser } = login;
    // 表格里的问题人员信息
    const tableProData = (text, record) => {
      if (Number(record.probFlag) === 1) {
        return (
          <Tooltip
            placement="top"
            title={
              <div>
                <p>
                  问题人员类型：
                  {record.probDetList && record.probDetList[0]
                    ? record.probDetList[0].probTypeName
                    : ''}
                </p>
                <p>
                  问题说明：
                  {record.probDetList && record.probDetList[0]
                    ? record.probDetList[0].probTypeDesc
                    : ''}
                </p>
              </div>
            }
          >
            <span>
              {text}
              <img src={proIcon} alt="" />
            </span>
          </Tooltip>
        );
      }
      return <span>{text}</span>;
    };
    // 表格里联系状态
    const tableDataFlag = record => {
      if (Number(record.overdueFlag) === 1) {
        return <span className={careerStyle.tableContactOver}>已逾期</span>;
      }
      if (Number(record.overdueFlag) === 2) {
        return <span className={careerStyle.tableContactTaday}>今日</span>;
      }
      return null;
    };
    // 表格里的办理状态社保公积金显示
    const hdlCompleteChild = item => {
      if (Number(item.submitExecFlag) === 1) {
        return (
          <Col span={8} key={item.ass}>
            <Checkbox disabled defaultValue={item.ass}>
              {item.assName}
            </Checkbox>
          </Col>
        );
      }
      if (Number(item.probFlag) === 1) {
        return (
          <Col span={8} key={item.ass}>
            <ExclamationCircleOutlined style={{ fontSize: 16, color: '#f00', marginRight: 5 }} />
            {item.assName}
          </Col>
        );
      }
      if (Number(item.submitExecFlag) === 2 && Number(item.probFlag) !== 1) {
        return (
          <Col span={8} key={item.ass}>
            <Checkbox value={item.ass}>{item.assName}</Checkbox>
          </Col>
        );
      }
      return null;
    };
    // 表格里的办理状态信息
    const hdlCompleteDom = () => {
      if (Number(pdArrList.insMergFlag) === 1) {
        return (
          <Col>
            {Number(pdArrList.probFlag) === 1 ? (
              <Col span={8}>
                <ExclamationCircleOutlined
                  style={{ fontSize: 16, color: '#f00', marginRight: 5 }}
                />
                社保
              </Col>
            ) : (
              <Col span={8}>
                <Checkbox value="3" disabled={Number(pdArrList.submitExecFlag) === 1}>
                  社保
                </Checkbox>
              </Col>
            )}
          </Col>
        );
      }
      if (pdArrList.socialArr && pdArrList.socialArr.length) {
        return pdArrList.socialArr.map(item => hdlCompleteChild(item));
      }
      return true;
    };

    // 动态表格
    const columns = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '联系状态',
        dataIndex: 'contStateName',
        onHeaderCell: () => ({
          style: widthFlag
            ? {
                fontWeight: 'bold',
                width: 180,
              }
            : { fontWeight: 'bold' },
        }),
      },
      {
        title: '材料状态',
        dataIndex: 'hdlStateName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
        render: text => text || '--',
      },
      {
        title: '申报状态',
        dataIndex: 'execStateName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '办理人',
        dataIndex: 'tskName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '所属客服',
        dataIndex: 'creName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
        render: text => text || '--',
      },
      {
        title: '派单时间',
        dataIndex: 'creTime',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            textAlign: 'center',
            fontWeight: 'bold',
          },
        }),
        sorter: true,
      },
      {
        title: '操作',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            textAlign: 'center',
            fontWeight: 'bold',
            width: 150,
          },
        }),
      },
    ];
    // 每列添加render
    const activeKeys = Number(activeKey);
    columns.map((item, i) => {
      const newItem = item;
      if (i === 0) {
        newItem.render = (text, record) => tableProData(text, record);
      }
      if (i === 1) {
        if (activeKeys === 1 || activeKeys === 2) {
          newItem.render = (val, record) => (
            <div>
              {val}
              {tableDataFlag(record)}
            </div>
          );
        } else {
          newItem.className = styles.hide;
        }
      }
      if (i === 3) {
        newItem.render = (text, record) => (
          <Tooltip title={this.tableDataTip(record)}>
            <span>{text}</span>
            <EllipsisOutlined style={{ fontSize: 14, color: '#08c' }} />
          </Tooltip>
        );
      }
      if (i === 6) {
        if (activeKeys === 2 || activeKeys === 3 || activeKeys === 4) {
          newItem.title = tableDateTit[activeKeys].title;
          newItem.dataIndex = tableDateTit[activeKeys].dataIndex;
        }
        newItem.render = text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : '--');
      }
      if (i === 7) {
        newItem.render = (text, record) => (
          <span>
            {activeKeys !== 4 ? (
              <span>
                <a onClick={() => this.collectMaterial(record)}>
                  {activeKeys === 3 ? '修改材料' : '开始办理'}
                </a>
                <Divider type="vertical" />
              </span>
            ) : null}
            <Link
              to={`/careermanage/career/detail?entryId=${record.entryId}&&activeKey=${activeKeys}`}
            >
              查看
            </Link>
          </span>
        );
      }
      return true;
    });

    // 联系
    const menuContact = (
      <Menu>
        {contactWayList.map(value => (
          <Menu.Item key={value.itemCode}>
            <a onClick={() => this.sendNote(value.itemCode)}>{value.itemName}</a>
          </Menu.Item>
        ))}
      </Menu>
    );
    // 更多
    const obj = {
      menu1: () => (
        <Menu>
          {checkPermissions('es:entry:exportEntryInfo') && (
            <Menu.Item>
              <a onClick={this.outExcel} loading={excelLoading}>
                导出
              </a>
            </Menu.Item>
          )}
          {checkPermissions('es:matSubmit:insertMatSub') && (
            <Menu.Item>
              <a onClick={this.batchDeal}>批量办理</a>
            </Menu.Item>
          )}
          {checkPermissions('es:entry:insertEntryContRcrd') && (
            <Menu.Item>
              <a onClick={() => router.push(`/careermanage/career/batchContact?activeKey=${1}`)}>
                批量联系
              </a>
            </Menu.Item>
          )}
        </Menu>
      ),
      menu2: () => (
        <Menu>
          {checkPermissions('es:matSubmit:insertMatSub') && (
            <Menu.Item>
              <a onClick={this.batchDeal}>批量办理</a>
            </Menu.Item>
          )}
          {checkPermissions('es:entry:insertEntryContRcrd') && (
            <Menu.Item>
              <a onClick={() => router.push(`/careermanage/career/batchContact?activeKey=${2}`)}>
                批量联系
              </a>
            </Menu.Item>
          )}
          {checkPermissions('es:entryProb:addProb') && (
            <Menu.Item>
              <a onClick={() => this.showModal(true)}>标记问题人员</a>
            </Menu.Item>
          )}

          {checkPermissions('es:entry:exportEntryInfo') && (
            <Menu.Item>
              <a onClick={this.outExcel} loading={excelLoading}>
                导出
              </a>
            </Menu.Item>
          )}
        </Menu>
      ),
    };
    const moreSumbit = activeKeyBtn => {
      let result;
      if (activeKeyBtn === 1) {
        result =
          checkPermissions('es:entry:exportEntryInfo') ||
          checkPermissions('es:matSubmit:insertMatSub');
      } else if (activeKeyBtn === 2) {
        result =
          checkPermissions('es:entryProb:addProb') || checkPermissions('es:entry:exportEntryInfo');
      }
      // 一个权限都没有就不显示下拉菜单
      if (result) {
        return (
          <Dropdown overlay={obj['menu'.concat(activeKeyBtn)]}>
            <Button className={styles.listBtn}>
              更多 <DownOutlined />
            </Button>
          </Dropdown>
        );
      }
    };
    // 表格按钮
    const tableButtomDom = activeKeyBtn => (
      <Row style={{ marginBottom: 16 }}>
        {activeKeyBtn === 2 ? (
          <Authorized authority="es:entry:toExecute">
            <Button className={styles.listBtn} onClick={this.batchToSumbit} type="primary">
              提交申报
            </Button>
          </Authorized>
        ) : null}
        {activeKeyBtn === 1 || activeKeyBtn === 2 ? (
          <Authorized authority="es:entry:insertEntryContRcrd">
            <Dropdown overlay={menuContact}>
              <Button className={styles.listBtn} type={activeKeyBtn === 1 ? 'primary' : null}>
                联系员工
                <DownOutlined style={{ fontSize: 12 }} />
              </Button>
            </Dropdown>
          </Authorized>
        ) : null}
        {activeKeyBtn === 1 ? (
          <Authorized authority="es:entry:signProbFlag">
            <Button className={styles.listBtn} onClick={() => this.showModal(true)}>
              标记问题人员
            </Button>
          </Authorized>
        ) : null}
        {activeKeyBtn === 1 || activeKeyBtn === 2 ? moreSumbit(activeKeyBtn) : null}
        {activeKeyBtn === 3 ? (
          <Authorized authority="es:entry:exportEntryInfo">
            <Button
              className={styles.listBtn}
              onClick={this.outExcel}
              type="primary"
              loading={excelLoading}
            >
              {!excelLoading && <DownloadOutlined />}
              导出
            </Button>
          </Authorized>
        ) : null}
        {activeKeyBtn === 5 ? (
          <React.Fragment>
            <Authorized authority="es:entryProb:addProbFdbk">
              <Button type="primary" onClick={this.batchFeedback} style={{ marginRight: 8 }}>
                批量反馈
              </Button>
            </Authorized>
            <ProExportBtn selectedRowKeys={selectedRowKeys} downloadParams={downloadParams} />
          </React.Fragment>
        ) : null}
      </Row>
    );
    const tabPane1 = (
      <div>
        {tableButtomDom(activeKeys)}
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={data}
          rowKey="entryId"
          columns={columns}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    const tabPane4 = (
      <div>
        {tableButtomDom(activeKeys)}
        {/* <ProTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          timeFlag
          loading={loading}
          data={proListData}
          rowKey="detId"
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
          proUrl={`${tempUrl}/problem`}
          isProObj
        /> */}
        <ProTable
          onRef={e => {
            this.setState({ proTable: e });
          }}
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          onSelectRow={this.handleSelectRows}
          proUrl={`${tempUrl}/problem`}
          busiType="1"
          isProObj
        />
      </div>
    );
    const tabPaneTem = ['', tabPane1, tabPane1, tabPane1, tabPane1, tabPane4];
    return (
      <PageHeaderWrapper>
        {/* 搜索框 */}
        <RenderForm
          {...{
            getFieldDecorator,
            activeKey,
            pageOrdBys,
            formFieldsValue,
            expandForm,
            login,
          }}
          getList={this.getList}
          resetSearch={this.resetSearch}
          toggleForm={this.toggleForm}
          userId={baseUser.userId}
        />
        <Card className={styles.tabCard}>
          <Tabs activeKey={activeKey} onChange={this.changeTabPane}>
            {tabList.map(pane => (
              <TabPane tab={pane.itemName} key={pane.itemCode} forceRender>
                {tabPaneTem[pane.itemCode]}
              </TabPane>
            ))}
          </Tabs>
          <ContactPhone
            {...{
              conatctVisible,
              expandConsult,
              contactFlag,
              conTel,
              empTel,
              selectedRows,
              multiterm,
            }}
            submitData={this.submitData}
            handleModalVisible={this.handleModalVisible}
            contactData={this.contactData}
            addConsultData={this.addConsultData}
          />
          <Modal
            title="提交申报"
            visible={execVisable}
            onOk={this.execOk}
            onCancel={this.execCancel}
            destroyOnClose
          >
            <Form>
              <Form.Item label="提交到社保" {...formItemLayout2}>
                {getFieldDecorator('pdArrSocial', {})(
                  <Checkbox.Group style={{ width: '100%' }}>
                    <Row>{hdlCompleteDom()}</Row>
                  </Checkbox.Group>
                )}
              </Form.Item>
              <Form.Item label="提交到公积金" {...formItemLayout2}>
                {getFieldDecorator('pdArrAccu', {})(
                  <Checkbox.Group style={{ width: '100%' }}>
                    <Row>
                      {pdArrList.accuArr && pdArrList.accuArr.length
                        ? pdArrList.accuArr.map(item => hdlCompleteChild(item))
                        : null}
                    </Row>
                  </Checkbox.Group>
                )}
              </Form.Item>
            </Form>
          </Modal>
          {/* <ProModal
            visible={proVisible}
            selectedRows={selectedRows}
            onOk={this.proHandleOk}
            onCancel={() => this.toggleProModal(false)}
            isProObj
            proObjData={proObjData}
            proStatus={proStatus}
            confirmLoading={confirmLoading}
          /> */}
          <Modal title="批量发送" footer={null} closable={false} visible={showProgress}>
            <div style={{ textAlign: 'center' }}>
              <div>
                <Progress
                  percent={progressPercent}
                  format={percent => `${percent}%`}
                  style={{ paddingRight: 24, marginBottom: 20 }}
                />
              </div>
            </div>
          </Modal>
          {/* <Modal
            title="批量发送"
            footer={null}
            closable={false}
            visible={progressVisible}
            onCancel={this.closeModal}
          >
            <div style={{ textAlign: 'center' }}>
              <div>
                <Progress
                  percent={progressPercent}
                  format={percent => `${percent}%`}
                  style={{ paddingRight: 24, marginBottom: 20 }}
                />
                <Button onClick={this.closeModal}>关闭</Button>
              </div>
            </div>
          </Modal> */}
          {proVisible && (
            <ProModal
              selectedRows={selectedRows}
              selectedRowKeys={selectedRowKeys}
              busiType="1"
              onOk={this.proHandleOk}
              onCancel={() => this.toggleProModal(false)}
              isProObj
              isProType
            />
          )}
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default TableList;
